﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SiteParser.Core
{
	public class HtmlRegexpExpressionBuilder : IExpressionBuilder
	{
		private const string SPACE = "\\s";
		private const string QUOTE = "\"'";
		private const string NOT_END_TAG = "[^>]*";
		private const string NOT_QUOTE = "[^\"']*";
		private const string ATTRIBUTE_TEMPLATE = "{0}\\s*=\\s*[\"']{1}[\"']";
		private const string RESULT_REGEXP_TEMPLATE = "<\\s*{0}[^>]*{1}[^>]*((/\\s*>)|(>)?)";

		private string BuildAttribute(string attributeName, string attributeValue, MatchType type) {
			switch (type) {
				case MatchType.StartWith:
					attributeValue += NOT_QUOTE;
					break;
				case MatchType.EndWith:
					attributeValue = NOT_QUOTE + attributeValue;
					break;
				case MatchType.Contain:
					attributeValue = NOT_QUOTE + attributeValue + NOT_QUOTE;
					break;
				case MatchType.MatchAll:
					attributeValue = NOT_QUOTE;
					break;

			}

			return string.Format(ATTRIBUTE_TEMPLATE, attributeName, attributeValue);
		}


		#region IExpressionBuilder Members

		public string BuildExpression(HtmlNavigationExpression htmlNavigationExpression) {
			if (htmlNavigationExpression == null) {
				throw new ArgumentNullException("htmlNavigationExpression");
			}

			StringBuilder htmlRegexpExpression = new StringBuilder();

			foreach (var filterItem in htmlNavigationExpression.AttributesFilter) {
				htmlRegexpExpression.Append(BuildAttribute(filterItem.Key, filterItem.Value.Name, filterItem.Value.Type));
			}

			return string.Format(RESULT_REGEXP_TEMPLATE, htmlNavigationExpression.TagMatchingRule.Name, htmlRegexpExpression);
		}

		#endregion
	}
}
